package com.magicalcoder.pigeontest.client.zookeeper;

import com.magicalcoder.pigeon.client.ClientHandlerManager;
import com.magicalcoder.pigeon.client.PigeonClient;
import com.magicalcoder.pigeon.common.callback.ZookeeperNodeWatchCallback;
import com.magicalcoder.pigeon.common.dto.RmtAddress;
import com.magicalcoder.pigeon.zookeeper.ClientFoundService;
import com.magicalcoder.pigeontest.model.Person;
import com.magicalcoder.pigeontest.service.HelloPersonService;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by hzhedongyu on 2017/5/27.
 * zookeeper做节点发现 自动调控
 */
public class ClientApp {
    public static void main(String[] args) {
        PigeonClient client = new PigeonClient();

        String serviceName = "userService";
        ClientFoundService clientFoundService = ClientFoundService.get();
        clientFoundService.watchZookeeper(new ZookeeperNodeWatchCallback() {
            @Override
            public void call(CopyOnWriteArrayList<RmtAddress> currentAliveAllServerList) {
                ClientHandlerManager.get().serverNodeChange(currentAliveAllServerList);
            }
        });

        AtomicInteger integer = new AtomicInteger(0);
        while (true){

            for(int i=0;i<10;i++){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        HelloPersonService helloPersonService = client.newInstance(HelloPersonService.class,serviceName);
                        try {
                            List<Person> person = helloPersonService.GetTestPerson("何栋宇",integer.getAndIncrement());
                            System.out.println(person.get(0).getLastName()+person.get(0).getFirstName());
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

//        System.out.println(result);
    }
}
